import time

import allure
from selenium.common import StaleElementReferenceException
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

from page.add_proxy_order_page import AddProxyOrderPage
from page.base_page import BasePage
from page.main_page import MainPage
from page.modify_proxy_order_page import ModifyProxyOrderPage


class ProxyOrderApply(BasePage):
    __financial_management = By.XPATH, "//*[text()='财务管理']"
    __disbursement_account = By.XPATH, "//*[text()='放款虚户']"
    __platform_account = By.XPATH, "//*[text()='平台虚户']"
    __post_loan_management = By.XPATH, "// *[text() = '贷后管理']"
    __post_loan_management_proxy = By.XPATH, "//*[text() = '贷后管理']/../../ul/div[2]"
    __compensation_notice = By.XPATH, "//*[@href = '/postLoanManagement/proxyPostLoan/proxyRecord']"
    __platform_account_detail = By.XPATH, '//*[@href="/financial/account/account/index"]'
    __APPROVE_PROXY_ORDER = By.XPATH, '//*[@href="/order/proxyOrder/proxyOrderCheck"]'
    __disbursement_account_detail = By.XPATH, '//*[@href="/financial/disbursementAccount/finAccount"]'
    __NAME = By.XPATH, "//*[@placeholder = '请输入借贷人姓名']"
    __PHONE = By.XPATH, "//*[@placeholder = '请输入借贷人手机号']"
    __SSN = By.XPATH, "//*[@placeholder = '请输入借贷人身份证号']"
    __NUMBER = By.XPATH, "//*[@placeholder = '请输入借贷编号']"
    __CAPITAL = By.XPATH, "//*[text()='请选择资金方']"
    __PRODUCT_NAME = By.XPATH, "//*[@placeholder = '请输入产品名称']"
    __ORDER_STATUS = By.XPATH, "//*[text()='请选择订单状态']"
    __CAPITAL_PLAN = By.XPATH, "//*[text()='请选择配资方案']"
    __CREATION_START_TIME = By.XPATH, "//*[@placeholder = '开始日期']"
    __CREATION_END_TIME = By.XPATH, "//*[@placeholder = '结束日期']"
    __SEARCH_BUTTON = By.XPATH, "//*[@class = 'el-button el-button--primary el-button--default']"
    __SEARCH_FIRST_NAME = By.XPATH, "//*[@class = 'el-table__row'][1]/td[2]/div"
    __SEARCH_FIRST_DETAILS = By.XPATH, "//*[@class = 'el-table__row'][1]/td[1]/div/a/span"
    __SEARCH_FIRST_CAPITAL = By.XPATH, "//*[@class = 'el-table__row'][1]/td[5]/div"
    __SEARCH_FIRST_ORDER_STATUS = By.XPATH, "//*[@class = 'el-table__row'][1]/td[4]/div/span/span"
    __SEARCH_FIRST_CAPITAL_PLAN = By.XPATH, "//*[@class = 'el-table__row'][1]/td[6]/div"
    __SEARCH_FIRST_CREATION_TIME = By.XPATH, "//*[@class = 'el-table__row'][1]/td[17]/div"
    __SEARCH_QUANTITY = By.XPATH, "//*[@class = 'el-pagination__total is-first']"
    __DETAILS_PHONE = By.XPATH, "//*[text()='手机号']/following-sibling::span[1]"
    __DETAILS_SSN = By.XPATH, "//*[text()='身份证']/following-sibling::span[1]"
    __DETAILS_PRODUCT_NAME = By.XPATH, "//*[@class = 'el-table__row'][1]/td[9]/div"
    __MAIN_PAGE_BUTTON = By.XPATH, "//*[@role = 'menuitem']/*[text()='首页']"
    __DETAILS_CLOSE_BUTTON = By.XPATH, "//*[@class = 'el-icon el-drawer__close']"
    __RESET_BUTTON = By.XPATH, "//*[text() ='重置']"
    __EXPORT_BUTTON = By.XPATH, "//*[text()='导出 ']/.."
    __CUE_WORD = By.XPATH, "//*[@class = 'el-message__content']"
    __ADD_BUTTON = By.XPATH, "//*[text()='新增 ']/.."
    __VIEW_REMARKS = By.XPATH, "//*[@class = 'el-table__row'][1]/td[16]/div/a"
    __REMARKS_TEXT = By.XPATH, "//*[@id = 'inform']/div[2]"
    __VIEW_REMARKS_CLOSE = By.XPATH, "//*[@id = 'inform']/div[1]/i"
    __CUSTOMER_TRACKING = By.XPATH, "//textarea"
    __CUSTOMER_TRACKING_SUBMIT = By.XPATH, "//*[@class = 'dialog-footer']/button"
    __CUSTOMER_TRACKING_TEXT = By.XPATH, "//*[@class = 'el-timeline-item__content']/div/div[2]"
    __MODIFY_BUTTON = By.XPATH, "//*[@class = 'el-table__row'][1]/td[21]//*[text()='修改']"
    __BAD_DEBT_BUTTON = By.XPATH, "//*[@class = 'el-table__row'][1]/td[21]//*[text()='呆账']"
    __OVERDUE_STATUS = By.XPATH, "//*[@class = 'el-table__row'][1]/td[13]/div"
    __BAD_DEBT_STATUS = By.XPATH, "//*[@class = 'el-table__row'][1]/td[14]/div"
    __COMPENSATORY_STATUS = By.XPATH, "//*[@class = 'el-table__row'][1]/td[15]/div"
    __SECOND_CONFIRM_BUTTON = By.XPATH, "//*[@role = 'dialog']//*[text()='确定']"
    __CANCEL_BUTTON = By.XPATH, "//*[@class = 'el-table__row'][1]/td[20]//*[text()='取消']"
    __CANCEL_APPROVE_BUTTON = By.XPATH, "//*[@class = 'el-table__row'][1]/td[21]//*[text()='取消复审']"
    __CANCEL_APPROVE_REASON = By.XPATH, "//*[text()='取消复审']/../../..//input"
    __CANCEL_APPROVE_OK = By.XPATH, "//*[text()='取消复审']/../../..//*[text()='确定']"
    __MODIFY_PROPERTY = By.XPATH, "//*[@class = 'el-table__row'][1]/td[21]//*[text()='修改房产']"
    __MODIFY_PROPERTY_SUBMIT = By.XPATH, "//*[text()='修改房产']/../../..//*[text()='确定']"
    __SIGN_THE_COMMITMENT_LETTER = By.XPATH, "//*[@class = 'el-table__row'][1]/td[21]//*[text()='签署承诺函']"
    __SIGN_THE_COMMITMENT_LETTER_STATUS = By.XPATH, "//*[@class = 'el-table__row'][1]/td[12]/div/span/span"
    __SIGN_THE_COMMITMENT_LETTER_OK = By.XPATH, "//*[text()='确定']/.."
    __REPAYMENT_PLAN_LAST_PERIOD = By.XPATH, ("//*[@class = 'el-row scroll-item-detail']//*[text()='还款计划']"
                                              "/../..//*[@class='el-table__row'][last()]/td[1]/div/div")
    __statistics_report = By.XPATH, "//*[text()='统计报表']"
    __proxy_report = By.XPATH, "//*[text()='代理报表']"
    __loan_statistics = By.XPATH, '//*[@href="/statistics/proxyReport/disburseStatisticsProxy"]'
    __repayment_statistics = By.XPATH, '//*[@href="/statistics/proxyReport/repayStatisticsProxy"]'
    __in_stock_statistics = By.XPATH, '//*[@href="/statistics/proxyReport/outstandingStatisticsProxy"]'
    __overdue_statistics = By.XPATH, '//*[@href="/statistics/proxyReport/overdueStatisticsProxy"]'

    def goto_loan_statistics(self):
        from page.loan_statistics_page import LoanStatistics
        with allure.step('点击统计报表'):
            self.find_and_click(self.__statistics_report)
        with allure.step('点击代理报表'):
            self.find_and_click(self.__proxy_report)
        with allure.step('点击放款统计'):
            self.find_and_click(self.__loan_statistics)
        return LoanStatistics(self.driver)

    def goto_approve_proxy(self):
        from page.approve_proxy_order_page import ApproveProxyOrderPage
        with allure.step('点击审批代理订单'):
            self.find_and_click(self.__APPROVE_PROXY_ORDER)
        return ApproveProxyOrderPage(self.driver)

    def goto_main_page(self):
        with allure.step('点击首页'):
            self.find_and_click(self.__MAIN_PAGE_BUTTON)
        return MainPage(self.driver)

    def goto_platform_account_detail(self):
        from page.platform_account_detail_page import PlatformAccountDetail
        with allure.step('点击财务管理'):
            self.find_and_click(self.__financial_management)
        with allure.step('点击平台虚户'):
            self.find_and_click(self.__platform_account)
        with allure.step('点击账户详情'):
            self.find_and_click(self.__platform_account_detail)
        return PlatformAccountDetail(self.driver)

    def goto_disbursement_account_detail(self):
        from page.disbursement_account_page import DisbursementAccount
        with allure.step('点击财务管理'):
            self.find_and_click(self.__financial_management)
        with allure.step('点击放款虚户'):
            self.find_and_click(self.__disbursement_account)
        with allure.step('点击账户详情'):
            self.find_and_click(self.__disbursement_account_detail)
        return DisbursementAccount(self.driver)

    def goto_repayment_statistics(self):
        from page.repayment_statistics_page import RepaymentStatistics
        with allure.step('点击统计报表'):
            self.find_and_click(self.__statistics_report)
        with allure.step('点击代理报表'):
            self.find_and_click(self.__proxy_report)
        with allure.step('点击还款统计'):
            self.find_and_click(self.__repayment_statistics)
        return RepaymentStatistics(self.driver)

    def goto_in_stock_statistics(self):
        from page.in_stock_statistics_page import InStockStatistics
        with allure.step('点击统计报表'):
            self.find_and_click(self.__statistics_report)
        with allure.step('点击代理报表'):
            self.find_and_click(self.__proxy_report)
        with allure.step('点击在库统计'):
            self.find_and_click(self.__in_stock_statistics)
        return InStockStatistics(self.driver)

    def goto_overdue_statistics(self):
        from page.overdue_statistics_page import OverdueStatistics
        with allure.step('点击统计报表'):
            self.find_and_click(self.__statistics_report)
        with allure.step('点击代理报表'):
            self.find_and_click(self.__proxy_report)
        with allure.step('点击逾期统计'):
            self.find_and_click(self.__overdue_statistics)
        return OverdueStatistics(self.driver)

    def goto_compensation_notice(self):
        from page.compensation_notice_page import CompensationNotice
        with allure.step('点击贷后管理'):
            self.find_and_click(self.__post_loan_management)
        with allure.step('点击代理'):
            self.find_and_click(self.__post_loan_management_proxy)
        with allure.step('点击代偿通知'):
            self.find_and_click(self.__compensation_notice)
        return CompensationNotice(self.driver)

    def search_name(self, name):
        with allure.step(f"输入{name}的姓名进行查询"):
            self.find_and_send(self.__NAME, text=name)
            self.find_and_click(self.__SEARCH_BUTTON)
        return ProxyOrderApply(self.driver)

    def search_phone(self, phone):
        with allure.step(f"输入{phone}手机号码进行查询"):
            self.find_and_send(self.__PHONE, text=phone)
            self.find_and_click(self.__SEARCH_BUTTON)
        return ProxyOrderApply(self.driver)

    def search_ssn(self, ssn):
        with allure.step(f"输入{ssn}身份证号码进行查询"):
            self.find_and_send(self.__SSN, text=ssn)
            self.find_and_click(self.__SEARCH_BUTTON)
        return ProxyOrderApply(self.driver)

    def search_number(self, number):
        with allure.step(f"输入{number}订单编号进行查询"):
            while True:
                try:
                    self.find(self.__NUMBER).clear()
                    self.find_and_send(self.__NUMBER, text=number)
                    self.find_and_click(self.__SEARCH_BUTTON)
                    break
                except:
                    pass
        return ProxyOrderApply(self.driver)

    def search_capital(self, capital):
        with allure.step(f"选择资金方{capital}"):
            self.find_and_click(self.__CAPITAL)
            self.find_and_click(By.XPATH, f"//*[@class ='el-scrollbar']//li/*[text() = '{capital}']")
            self.find_and_click(self.__SEARCH_BUTTON)
        return ProxyOrderApply(self.driver)

    def search_product_name(self, product_name):
        with allure.step(f"输入{product_name}产品名称进行查询"):
            self.find_and_send(self.__PRODUCT_NAME, text=product_name)
            self.find_and_click(self.__SEARCH_BUTTON)
        return ProxyOrderApply(self.driver)

    def search_order_status(self, order_status):
        with allure.step(f"选择订单状态{order_status}"):
            self.find_and_click(self.__ORDER_STATUS)
            self.find_and_click(By.XPATH, f"//*[@class ='el-scrollbar']//li/*[text() = '{order_status}']")
            self.find_and_click(self.__SEARCH_BUTTON)
        return ProxyOrderApply(self.driver)

    def search_capital_plan(self, capital_plan):
        with allure.step(f"选择配资方案{capital_plan}"):
            self.find_and_click(self.__CAPITAL_PLAN)
            self.find_and_click(By.XPATH, f"//*[@class ='el-scrollbar']//li/*[text() = '{capital_plan}']")
            self.find_and_click(self.__SEARCH_BUTTON)
        return ProxyOrderApply(self.driver)

    def search_creation_time(self, creation_start_time, creation_end_time):
        with allure.step(f"选择创建时间{creation_start_time}至{creation_end_time}进行查询"):
            self.find_and_send(self.__CREATION_START_TIME, text=creation_start_time)
            self.find_and_send(self.__CREATION_END_TIME, text=creation_end_time)
            self.find_and_send(self.__CREATION_END_TIME, text=Keys.ENTER)
            self.find_and_click(self.__SEARCH_BUTTON)
        return ProxyOrderApply(self.driver)

    def click_search_button(self):
        with allure.step("点击查询按钮"):
            self.find_and_click(self.__SEARCH_BUTTON)
        return ProxyOrderApply(self.driver)

    def goto_search_results_details(self):
        with allure.step("点击当前查询结果第一位的订单详情"):
            self.find_and_click(self.__SEARCH_FIRST_DETAILS)
        return ProxyOrderApply(self.driver)

    def close_details(self):
        with allure.step("点击详情页关闭按钮"):
            ele = self.finds(self.__DETAILS_CLOSE_BUTTON)[0]
            ele.click()
        return ProxyOrderApply(self.driver)

    def get_search_results_name(self):
        with allure.step("获取当前查询结果第一位的姓名"):
            time.sleep(0.2)
            search_first_name = self.find(self.__SEARCH_FIRST_NAME).text
        return search_first_name

    def get_search_results_phone(self):
        with allure.step("获取当前订单手机号码"):
            search_first_phone = self.find(self.__DETAILS_PHONE).text
        return search_first_phone

    def get_search_results_ssn(self):
        with allure.step("获取当前订单身份证号码"):
            search_first_phone = self.find(self.__DETAILS_SSN).text
        return search_first_phone

    def get_search_results_number(self):
        with allure.step("获取当前订单编号"):
            time.sleep(0.2)
            search_first_number = self.find(self.__SEARCH_FIRST_DETAILS).text
        return search_first_number

    def get_search_results_capital(self):
        with allure.step("获取当前资金方公司"):
            time.sleep(0.2)
            search_first_capital = self.find(self.__SEARCH_FIRST_CAPITAL).text
        return search_first_capital

    def get_search_results_product_name(self):
        with allure.step("获取当前产品名称"):
            time.sleep(0.2)
            search_first_product_name = self.find(self.__DETAILS_PRODUCT_NAME).text
        return search_first_product_name

    def get_search_results_order_status(self):
        with allure.step("获取当前订单状态"):
            while True:
                try:
                    search_first_order_status = self.find(self.__SEARCH_FIRST_ORDER_STATUS).text
                    break
                except StaleElementReferenceException:
                    continue
        return search_first_order_status

    def get_search_results_capital_plan(self):
        with allure.step("获取当前配资方案"):
            search_first_capital_plan = self.find(self.__SEARCH_FIRST_CAPITAL_PLAN).text
        return search_first_capital_plan

    def get_search_results_creation_time(self):
        with allure.step("获取当前创建时间"):
            search_first_creation_time = self.find(self.__SEARCH_FIRST_CREATION_TIME).text
        return search_first_creation_time

    def get_search_quantity(self):
        with allure.step("获取当前查询结果数量"):
            search_quantity = self.find(self.__SEARCH_QUANTITY).text
        return search_quantity

    def click_reset_button(self):
        with allure.step("点击重置按钮"):
            self.find_and_click(self.__RESET_BUTTON)
        return ProxyOrderApply(self.driver)

    def export_button(self):
        with allure.step("点击导出按钮"):
            self.find_and_click(self.__EXPORT_BUTTON)
        return ProxyOrderApply(self.driver)

    def get_cue_word(self):
        with allure.step("获取提示词"):
            cue_word = self.find(self.__CUE_WORD).text
        return cue_word

    def add_button(self):
        with allure.step("点击新增按钮"):
            self.find_and_click(self.__ADD_BUTTON)
        return AddProxyOrderPage(self.driver)

    def view_remarks(self):
        with allure.step("点击备注下方的查看按钮"):
            self.find_and_click(self.__VIEW_REMARKS)
            time.sleep(0.2)
            result = self.find(self.__REMARKS_TEXT).text
            self.find_and_click(self.__VIEW_REMARKS_CLOSE)
        return result

    def input_customer_tracking(self, customer_tracking):
        with allure.step("输入客户跟踪"):
            self.find_and_send(self.__CUSTOMER_TRACKING, text=customer_tracking)
            self.find_and_click(self.__CUSTOMER_TRACKING_SUBMIT)
        return ProxyOrderApply(self.driver)

    def get_customer_tracking_text(self):
        with allure.step("获取客户跟踪文本"):
            customer_tracking_text = self.find(self.__CUSTOMER_TRACKING_TEXT).text
        return customer_tracking_text

    def modify_order(self):
        with allure.step("点击第一条订单的修改按钮"):
            self.find_and_click(self.__MODIFY_BUTTON)
        return ModifyProxyOrderPage(self.driver)

    def bad_debt_button(self):
        with allure.step("点击第一条订单的呆账按钮"):
            self.find_and_click(self.__BAD_DEBT_BUTTON)
            self.find_and_click(self.__SECOND_CONFIRM_BUTTON)
        return ProxyOrderApply(self.driver)

    def get_overdue_status(self):
        with allure.step("获取第一条订单的逾期状态"):
            bad_debt_status = self.find(self.__OVERDUE_STATUS).text
        return bad_debt_status

    def get_bad_debt_status(self):
        with allure.step("获取第一条订单的呆账状态"):
            bad_debt_status = self.find(self.__BAD_DEBT_STATUS).text
        return bad_debt_status

    def get_compensatory_status(self):
        with allure.step("获取第一条订单的代偿状态"):
            compensatory_status = self.find(self.__COMPENSATORY_STATUS).text
        return compensatory_status

    def cancel_order(self):
        with allure.step("点击第一条订单的取消按钮"):
            self.find_and_click(self.__CANCEL_BUTTON)
            self.find_and_click(self.__SECOND_CONFIRM_BUTTON)
        return ProxyOrderApply(self.driver)

    def cancel_second_approve(self):
        with allure.step("点击第一条订单的取消复审按钮"):
            self.find_and_click(self.__CANCEL_APPROVE_BUTTON)
            self.find_and_send(self.__CANCEL_APPROVE_REASON, text="取消复审原因")
            self.find_and_click(self.__CANCEL_APPROVE_OK)
        return ProxyOrderApply(self.driver)

    def modify_property(self):
        with allure.step("点击第一条订单的修改房产按钮"):
            self.find_and_click(self.__MODIFY_PROPERTY)
            self.find_and_click(self.__MODIFY_PROPERTY_SUBMIT)
        return ProxyOrderApply(self.driver)

    def get_repayment_plan_last_period(self):
        with allure.step("获取订单的还款计划最后一期"):
            repayment_plan_last_period = self.find(self.__REPAYMENT_PLAN_LAST_PERIOD).text
        return repayment_plan_last_period

    def get_repayment_plan_period_status(self, period):
        with allure.step(f"获取订单还款计划第{period}期的状态"):
            while True:
                try:
                    repayment_plan_last_period_status = self.find(
                        By.XPATH, f"//*[text()='还款计划']/../../div[3]//tbody/tr[{period}]/td[2]/div/div/span/span"
                    ).text
                    break
                except StaleElementReferenceException:
                    continue
        return repayment_plan_last_period_status

    def get_repayment_plan_period_compensatory_patterns(self, period):
        with allure.step(f"获取订单还款计划第{period}期的代偿形式"):
            while True:
                try:
                    repayment_plan_period_compensatory_patterns = self.find(
                        By.XPATH, f"//*[text()='还款计划']/../../div[3]//tbody/tr[{period}]/td[9]/div"
                    ).text
                    break
                except StaleElementReferenceException:
                    continue
        return repayment_plan_period_compensatory_patterns

    def click_sign_the_commitment_letter(self):
        with allure.step("点击第一条订单的签署承诺函按钮"):
            self.find_and_click(self.__SIGN_THE_COMMITMENT_LETTER)
            self.wait(EC.element_to_be_clickable(self.__SIGN_THE_COMMITMENT_LETTER_OK))
            self.find_and_click(self.__SIGN_THE_COMMITMENT_LETTER_OK)
        return ProxyOrderApply(self.driver)

    def get_sign_the_commitment_letter_status(self):
        with allure.step("获取第一条订单的签署承诺函状态"):
            while True:
                try:
                    sign_the_commitment_letter_status = self.find(self.__SIGN_THE_COMMITMENT_LETTER_STATUS).text
                    break
                except StaleElementReferenceException:
                    continue
        return sign_the_commitment_letter_status

    def click_bad_dept_button(self):
        with allure.step("点击第一条订单的呆账按钮"):
            self.find_and_click(self.__BAD_DEBT_BUTTON)
            self.find_and_click(self.__SECOND_CONFIRM_BUTTON)
        return ProxyOrderApply(self.driver)

    def get_bad_dept_status(self):
        with allure.step("获取第一条订单的呆账状态"):
            bad_dept_status = self.find(self.__BAD_DEBT_STATUS).text
        return bad_dept_status
